package com.example.recruit.controller;


import com.example.recruit.common.R;
import com.example.recruit.entity.User;
import com.example.recruit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 简历
 */
@RestController
@RequestMapping("/resume")
@CrossOrigin(origins = "*")
@Slf4j
public class ResumeController {

    @Value("${recruit.path}")
    private String basePath;

    @Autowired
    UserService userService;


    /**
     * 简历上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> uploadFile(String id,MultipartFile file){
        log.info("id"+id);
        User user = userService.getById(id);
        if(user==null){
            return R.error("上传失败");
        }
        String baseFile=file.getOriginalFilename();
        String suffix=baseFile.substring(baseFile.lastIndexOf("."));
        if(!".pdf".equals(suffix)){
            return R.error("请上传pdf格式的文件");
        }
        String filename= UUID.randomUUID()+suffix;
        log.info(filename);
        user.setResume(filename);
        userService.updateById(user);
        File dir=new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    /**
     * 简历下载
     * @param
     * @param response
     */
    @GetMapping("/download")
    public  void download(String id, HttpServletResponse response){
        User user = userService.getById(id);
        String name=user.getResume();
        //输入流读取文件内容
        log.info(name);
        try {
            File file=new  File(basePath+name);
            FileInputStream fileInputStream=new FileInputStream(file);
            //输出流，将文件写回浏览器，展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setHeader("Content-Type","application/pdf");
            response.addHeader("Content-Disposition","attachment;filename=" + new String(file.getName().getBytes(),"utf-8"));
            response.addHeader("Content-Length","" + file.length());
            byte[] bytes=new byte[2048];
            int len=0;
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
